package com.imooc.course.${model}.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.course.${model}.dao.${Domain}Dao;
import com.imooc.course.${model}.dto.${Domain}Dto;
import com.imooc.course.${model}.dto.PageDto;
import com.imooc.course.${model}.entity.${Domain};
import com.imooc.course.${model}.entity.${Domain}Example;
import com.imooc.course.${model}.service.${Domain}Service;
import com.imooc.course.${model}.utils.CopyUtil;
import com.imooc.course.${model}.utils.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service("${domain}Service")
public class ${Domain}ServiceImpl implements ${Domain}Service {

    private static final Logger log = LoggerFactory.getLogger(${Domain}ServiceImpl.class);

    @Resource(name = "${domain}Dao")
    private ${Domain}Dao ${domain}Dao;

    /**
     * 列表查询
     * @param pageDto
     */
    @Override
    public void getList(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());

        ${Domain}Example ${domain}Example = new ${Domain}Example();
        <#list fieldList as field>
            <#if field.nameHump == 'sort'>
        ${domain}Example.setOrderByClause("sort asc");
            </#if>
        </#list>
        List<${Domain}> ${domain}List = ${domain}Dao.selectByExample(${domain}Example);

        PageInfo<${Domain}> ${domain}PageInfo = new PageInfo<>(${domain}List);
        pageDto.setTotal(${domain}PageInfo.getTotal());

        List<${Domain}Dto> ${domain}DtoList = CopyUtil.copyList(${domain}List, ${Domain}Dto.class);

        pageDto.setList(${domain}DtoList);
    }

    /**
     * 保存，id有值为更新，id无值为新增
     * @param ${domain}Dto
     */
    @Override
    public void save(${Domain}Dto ${domain}Dto) {
        ${Domain} copy = CopyUtil.copy(${domain}Dto, ${Domain}.class);
        String id = ${domain}Dto.getId() != null ? ${domain}Dto.getId().trim() : ${domain}Dto.getId();
        if (StringUtils.isEmpty(id)) {
            this.add${Domain}(copy);
        }else{
            this.update${Domain}(copy);
        }
    }

    private void update${Domain}(${Domain} copy) {
        ${domain}Dao.updateByPrimaryKeySelective(copy);
    }

    private void add${Domain}(${Domain} copy) {
        copy.setId(UuidUtil.getShortUuid());
        ${domain}Dao.insertSelective(copy);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        ${domain}Dao.deleteByPrimaryKey(id);
    }
}
